﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Chenglin.WPMyStep.Resources;

namespace Chenglin.WPMyStep
{
    public partial class HistoryPage : PhoneApplicationPage
    {
        public HistoryPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            historyContainer.Children.Clear();

            var records = StepRecord.GetRecordFiles();
            if (records.Length == 0)
            {
                TextBlock tb = new TextBlock();
                tb.Text = AppResources.NoRecordsInStorage;
                tb.Style = (Style)Application.Current.Resources["PhoneTextSubtleStyle"];
                historyContainer.Children.Add(tb);
            }
            else
            {
                int pos = records.Length;
                foreach (DateTime recordTime in records.Reverse())
                {
                    StackPanel stackPanel = new StackPanel();
                    stackPanel.Style = (Style)Application.Current.Resources["historyEntryContainerStyle"];
                    stackPanel.Children.Add(new TextBlock { Style = (Style)Application.Current.Resources["PhoneTextLargeStyle"], Text = string.Format(AppResources.RecordTitle, pos--) });
                    stackPanel.Children.Add(new TextBlock { Style = (Style)Application.Current.Resources["PhoneTextSubtleStyle"], Text = recordTime.ToString() });
                    historyContainer.Children.Add(stackPanel);

                    stackPanel.Tap += delegate
                    {
                        ShowStepPage.Record = StepRecord.ReadFromFile(recordTime);
                        NavigationService.Navigate(new Uri("/ShowStepPage.xaml", UriKind.Relative));
                    };
                }
            }
        }
    }
}